package com.jy.adscm.operation.base.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.jy.adscm.annotation.AdscmLogger;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.base.bean.TaskManager;
import com.jy.adscm.operation.base.bean.TaskManagerAttchment;
import com.jy.adscm.operation.base.service.TaskManagerAttchmentService;
import com.jy.adscm.operation.base.service.TaskManagerService;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.support.SimpleCoreResponse;
import com.jy.adscm.system.utils.AdscmSystemUtils;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.zltx.service.SjAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyy
 * @since 2019-01-21
 */
@RestController
@RequestMapping("/adscm/operation/taskManagerAttchment")
public class TaskManagerAttchmentController {
    @Value("${operation.taskManager.upload-path}")
    private  String annexUploadPath;//附件上传路径
    @Autowired
    RedisTemplate<Object, Token> tokenRedisTemplate;
    @Autowired
    TaskManagerAttchmentService taskManagerAttchmentService;
    @Autowired
    TaskManagerService taskManagerService;
    @AdscmLogger("缔造价值上传附件")
    @RequestMapping("upload")
    public SimpleCoreResponse uploadSjAttachment(HttpServletRequest request) throws AdscmSystemException, IOException {
        String tokenId = request.getParameter("tokenId");
        String taskManagerAttchmentstr = request.getParameter("taskManagerAttchment");
        if (taskManagerAttchmentstr==null||"".equals(taskManagerAttchmentstr)){
            throw  new AdscmSystemException("TaskManagerAttchment 没得");
        }
        ObjectMapper mapper = new ObjectMapper();
        TaskManagerAttchment taskManagerAttchment = mapper.readValue(taskManagerAttchmentstr, TaskManagerAttchment.class);
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        List<String> paths = null;
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            String path = annexUploadPath /*+ File.separator*/ + UUID.randomUUID().toString().replaceAll("-","") + File.separator;

            paths = AdscmSystemUtils.getInstance().uploadFileNoNewName(multiRequest,path);
        }
        if (paths!=null){
            String path = paths.get(0);
            taskManagerAttchment.setFilePath(path);
            String  fileName =  path.substring(path.lastIndexOf("\\") + 1);
            taskManagerAttchment.setFileName(fileName);
            taskManagerAttchment.setUploadTime(new Date());
            taskManagerAttchment.setUploadPerson(token.getUser().getId().toString());
        }
        TaskManager taskManager = taskManagerService.selectById(taskManagerAttchment.getTid());
        if (taskManager.getPerformer().equals(String.valueOf(token.getUser().getId()))){
            taskManagerService.updateByPerformer(Integer.valueOf(taskManagerAttchment.getTid()));
        }
        if (taskManager.getCreator().equals(String.valueOf(token.getUser().getId()))){
            taskManagerService.updateByCreator(Integer.valueOf(taskManagerAttchment.getTid()));
        }
        return new SimpleCoreResponse("200","上传成功",taskManagerAttchmentService.insert(taskManagerAttchment));
    }
    @AdscmLogger("缔造价值下载附件")
    @RequestMapping("download/{id}")
    public  SimpleCoreResponse downloadSjAttachment(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)throws AdscmSystemException {
        TaskManagerAttchment sjAttachment = taskManagerAttchmentService.selectById(id);
        if (sjAttachment==null){
            throw  new AdscmSystemException("没找到文件");
        }
        AdscmSystemUtils.getInstance().downloadFile(sjAttachment.getFilePath(),response);
        return new SimpleCoreResponse("200","下载成功",null);
    }

    @RequestMapping("selectByFileId/{fileId}")
    public  SimpleCoreResponse  selectTaskManagerAttchments(@PathVariable Integer fileId)throws AdscmSystemException{
        List<TaskManagerAttchment> taskManagerAttchment=taskManagerAttchmentService.selectByFileId(fileId);
        if (taskManagerAttchment==null){
            taskManagerAttchment=new ArrayList<>();
        }
        return  new SimpleCoreResponse("200","查询成功",taskManagerAttchment);
    }
    @AdscmLogger("缔造价值删除附件")
    @RequestMapping("delete/{id}")
    public  SimpleCoreResponse  delete(@PathVariable Integer id ,HttpServletRequest request)throws AdscmSystemException{
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
          Boolean result=  taskManagerAttchmentService.deleteTaskManagerAttchments(id,token);
        return  new SimpleCoreResponse("200","查询成功",result);
    }
}

